#!/usr/bin/env node
/**
 * Phase3 字段类型校验报告生成器
 * 用法：node scripts/phase3/generate-field-type-validation.js ComponentName
 */

const fs = require('fs');
const path = require('path');

const CATEGORY_RULES = [
  { name: 'icon', test: name => /icon/i.test(name), expected: 'IconItem[]', guide: '第4节 Icon字段标准' },
  { name: 'image', test: name => /(img|image)$/i.test(name), expected: '{src:string;width:number;height:number}', guide: '第5节 Image字段标准' },
  { name: 'booleanYN', test: name => /^has|^need|^allow/i.test(name), expected: `'Y'|'N'`, guide: '第1节 Boolean字段规范' },
  { name: 'boolean', test: name => /^show/i.test(name), expected: 'boolean', guide: '第1节 Boolean字段规范' },
  { name: 'color', test: name => /color/i.test(name), expected: 'string', guide: '第2节 Color字段规范' },
  { name: 'spacing', test: name => /(margin|padding|radius|corner)/i.test(name), expected: 'string | number', guide: '第6节 Spacing字段规范' }
];

function loadSchema(componentName) {
  const schemaPath = path.join(process.cwd(), componentName, 'phase2/preview-props-schema.json');
  if (!fs.existsSync(schemaPath)) {
    throw new Error(`preview-props-schema.json 不存在: ${schemaPath}`);
  }
  return JSON.parse(fs.readFileSync(schemaPath, 'utf8'));
}

function inferCategory(fieldName) {
  const rule = CATEGORY_RULES.find(rule => rule.test(fieldName));
  return rule || { name: 'generic', expected: 'string', guide: '通用字段规范' };
}

function normalize(typeText = '') {
  return typeText.replace(/\s+/g, '').toLowerCase();
}

function compareTypes(expected, actual) {
  if (!actual) return false;
  return normalize(expected) === normalize(actual);
}

function main() {
  const componentName = process.argv[2];
  if (!componentName) {
    console.error('用法: node scripts/phase3/generate-field-type-validation.js <ComponentName>');
    process.exit(1);
  }

  try {
    console.log(`\n🧪 生成字段类型校验报告: ${componentName}`);
    const schema = loadSchema(componentName);
    const props = schema.propsInterface || schema.props || {};

    const results = [];
    let passCount = 0;

    Object.entries(props).forEach(([field, def]) => {
      const category = inferCategory(field);
      const actualType = def.type || 'unknown';
      const passed = compareTypes(category.expected, actualType);
      if (passed) passCount++;

      results.push({
        field,
        category: category.name,
        expectedType: category.expected,
        actualType,
        dataTypeGuideSection: category.guide,
        status: passed ? 'pass' : 'fail'
      });
    });

    const summary = {
      totalChecked: results.length,
      passed: passCount,
      failed: results.length - passCount,
      passRate: results.length ? passCount / results.length : 1
    };

    const report = {
      componentCode: componentName,
      timestamp: new Date().toISOString(),
      validationResults: results,
      summary,
      blockers: results.filter(r => r.status === 'fail').map(r => `字段 ${r.field} 类型不匹配`),
      mustFixBeforeStep3: summary.failed > 0
    };

    const outputPath = path.join(process.cwd(), componentName, 'phase3/field-type-validation.json');
    fs.mkdirSync(path.dirname(outputPath), { recursive: true });
    fs.writeFileSync(outputPath, JSON.stringify(report, null, 2));
    console.log(`  ✅ 写入 ${outputPath}`);
  } catch (error) {
    console.error(`❌ 生成失败: ${error.message}`);
    process.exit(1);
  }
}

main();
